home *** CD-ROM | disk | FTP | other *** search
- Path: ix.netcom.com!netnews
- From: jlilley@ix.netcom.com (John Lilley)
- Newsgroups: comp.lang.c++
- Subject: Re: friend functions and access to private variables...
- Date: 14 Mar 1996 06:08:25 GMT
- Organization: Netcom
- Message-ID: <4i8d4p$57m@ixnews3.ix.netcom.com>
- References: <Dnyy92.MLL@news.uwindsor.ca>
- NNTP-Posting-Host: den-co20-12.ix.netcom.com
- Mime-Version: 1.0
- Content-Type: Text/Plain; charset=US-ASCII
- X-NETCOM-Date: Wed Mar 13 10:08:25 PM PST 1996
- Keywords: friend
- X-Newsreader: WinVN 0.99.7
-
- In article <Dnyy92.MLL@news.uwindsor.ca>, saed@engn.uwindsor.ca says...
- >
- >Dariusz Piatkowski asked:
- >>I'm dealing with two classes, where a member function of class A
- >> is declared as a friend function of class B.
- >>Unfortunately this does not allow the friend function access to private >>variables
- in class B...
-
- >--- A friend method of a non friend class has no access to the private member data.
- > Apparently the class to which that method belongs must be a friend. The friend
- > declaration of that method is then redundant.
- >
- >The code snippet below (compilable) will show what works and what doesn't.
- >
- >Aryan.
- >
- >//---- begin code
- >class X {
- > friend void yMethod(X x);
- > friend void aFunction(X x);
- > friend class Z;
- > private: int a;
- > };
- >
- >void aFunction(X x){x.a=1;};
- >// okay: aFunction is friend of class X and may access private member 'a' of X
- >
- >class Z { public: void zMethod(X x){x.a=1;}; };
- >// okay: class Z is friend of X, zMethod may access private member 'a' of X
- >
- >class Y { public: void yMethod(X x){x.a=1;}; };
- >// error: member `a' is a private member of class `X' (class Y is not a friend)
- >// this is Dariusz's question
- >
- >void aFunction(X x, int i){ return x.a=1; };
- >// error: member `a' is a private member of class `X'
- >// (different signature, not a friend)
- >
-
-
-
- This is not correct. Class methods may be friends of classes without
- its class being a friend. However, you must give the class scope of
- the method using '::', as follows:
-
- class X;
-
- class Y { public: void yMethod(X x); };
-
- class X {
- friend void Y::yMethod(X x);
- friend void aFunction(X x);
- friend class Z;
- private: int a;
- };
-
- void Y::yMethod(X x) {x.a=1;}
- // okay: Y::yMethod(X x) was declared a friend
-
- void aFunction(X x){x.a=1;};
- // okay: aFunction is friend of class X and may access private member 'a' of X
-
- class Z { public: void zMethod(X x){x.a=1;}; };
- // okay: class Z is friend of X, zMethod may access private member 'a' of X
-
-
- john lilley
- Nerds for Hire, Inc.
-
-